<?php

namespace app\api\controller\Product;

use think\Controller;
use think\Request;

class Order extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->OrderModel = model('Product.Order');
        $this->OrderProductModel = model('Product.OrderProduct');
        $this->CartModel = model('Product.Cart');
        $this->UserModel = model('User.User');
        $this->RecordModel = model('Record');
        $this->ProductModel = model('Product.Product');
        $this->UserAddressModel = model('User.Address');
    }

    //提交订单数据
    public function confirm()
    {
        //罗列传过来的数据
        $userid = $this->request->param('userid');
        $ids = $this->request->param('ids');
        $addrid = $this->request->param('addrid');
        $content = $this->request->param('content');

        //查询订单商品表是否有数据
        $CartList = $this->CartModel->with('product')->whereIn('cart.id', $ids)->where(['userid' => $userid])->select();
        if (!$CartList) {
            $this->error('所选的商品不存在，请重新选择');
        }
        //查询用户是否存在
        $user = $this->UserModel->find($userid);
        if (!$user) {
            $this->error('用户不存在，请注册');
        }
        //查询是否有收货地址
        $address = $this->UserAddressModel->find($addrid);
        if (!$address) {
            $this->error('所选的收货地址不存在，请重新选择');
        }

        /**
         * 购物车 => 删除
         * 订单表 => 新增订单 1
         * 订单商品 => 把购物车的数据添加订单商品表 1
         * 更新用户积分
         * 新增消费记录
         * 更新商品库存
         */

        //订单总价
        $total = 0;
        //消费剩余积分
        foreach ($CartList as $key => $item) {
            //购买商品数量是否小于商品库存
            if ($item['nums'] > $item['product']['stock']) {
                $this->error($item['product']['name'] . '商品库存不足，请重新选择');
            }

            //用户的积分是否足够
            $point = bcsub($user['point'], $item['total']);
            if ($point < 0) {
                $this->error('您的积分不足，请及时充值');
            }

            //计算出订单总价
            $total += $item['total'];
        }

        // 开启事务
        $this->OrderModel->startTrans();
        $this->OrderProductModel->startTrans();
        $this->CartModel->startTrans();
        $this->UserModel->startTrans();
        $this->RecordModel->startTrans();
        $this->ProductModel->startTrans();

        // 订单数据
        $OrderData = [
            'total' => $total,
            'userid' => $userid,
            'addrid' =>  $addrid,
            'code' => build_code('ASK'),
            'content' => $content,
            'status' => 1
        ];

        $OrderStatus = $this->OrderModel->validate('common/Product/Order')->save($OrderData);

        if ($OrderStatus === FALSE) {
            $this->error($this->OrderModel->getError());
        }

        // 订单商品数据
        $OrderProductData = [];

        foreach ($CartList as $item) {
            $OrderProductData[] = [
                'orderid' => $this->OrderModel->id,
                'proid' => $item['product']['id'],
                'nums' => $item['nums'],
                'price' => $item['price'],
                'total' => $item['total'],
                'userid' => $userid
            ];
        }

        $OrderProductStatus = $this->OrderProductModel->validate('common/Product/OrderProduct')->saveAll($OrderProductData);
        //验证商品订单状态
        if ($OrderProductStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->error($this->OrderProductModel->getError());
        }

        // 删除购物车
        $CartStatus = $this->CartModel->WhereIn('id', $ids)->delete();

        if ($CartStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->error($this->CartModel->getError());
        }

        //更新用户积分
        $UserData = ['id' => $userid, 'point' => bcsub($user['point'], $total)];
        $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);
        if ($UserStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->error($this->UserModel->getError());
        }

        //新增消费记录
        $RecordData = [
            // 'id' => $RecordId + 1,
            'userid' => $userid,
            'point' => $total,
            'createtime' => strtotime(date('Y-m-d H:i:s', time())),
            'content' => "您的商品订单{$OrderData['code']}共消费了{$total}积分",
            'state' => 5
        ];
        $RecordStatus = $this->RecordModel->validate('common/User/Record')->insert($RecordData);

        if ($RecordStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->UserModel->rollback();
            $this->error($this->RecordModel->getError());
        }

        //更新商品库存
        $ProductData = [];
        foreach ($CartList as $key => $item) {
            //购买商品数量是否小于商品库存
            if ($item['nums'] > $item['product']['stock']) {
                $this->error($item['product']['name'] . '商品库存不足，请重新选择');
            }
            $ProductData[] = ['id' => $item['product']['id'], 'stock' => bcsub($item['product']['stock'], $item['nums'])];
        }
        $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);
        if ($ProductStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->UserModel->rollback();
            $this->RecordModel->rollback();
            $this->error($this->ProductModel->getError());
        }
        if ($OrderStatus === FALSE || $OrderProductStatus === FALSE || $CartStatus === FALSE || $UserStatus === FALSE || $RecordStatus === FALSE || $ProductStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->UserModel->rollback();
            $this->RecordModel->rollback();
            $this->ProductModel->rollback();
            $this->error('下单失败');
        } else {
            $this->OrderModel->commit();
            $this->OrderProductModel->commit();
            $this->CartModel->commit();
            $this->UserModel->commit();
            $this->RecordModel->commit();
            $this->ProductModel->commit();
            //订单提交成功
            $this->success('支付订单成功', null, ['orderid' => $this->OrderModel->id]);
        }
    }

    //查询全部信息
    public function index()
    {
        $userid = $this->request->param('userid');

        $status = $this->request->param('status');

        $where = [];

        if (!empty($userid)) {
            $where['userid'] = $userid;
        }

        if ($status != 0) {
            $where['status'] = $status;
        }

        $orderList = $this->OrderModel->where($where)->select();

        foreach ($orderList as $item) {
            $OrderProduct = $this->OrderProductModel->with('product')->where('orderid', $item['id'])->select();

            $item['OrderProduct'] = $OrderProduct;
        }

        $this->success('查询成功', null, $orderList);
    }

    //删除订单
    public function delorder()
    {
        $orderid = $this->request->param('orderid', 0);
        $Order = $this->OrderModel->find($orderid);
        if (!$Order) {
            $this->error('该订单不存在');
        }
        $OrderProduct = $this->OrderProductModel->where('orderid', $orderid)->select();
        $OrderProId = [];
        foreach ($OrderProduct as $item) {
            $OrderProId[] = $item['id'];
        }
        if (!$OrderProduct) {
            $this->error('该订单详情不存在');
        }
        $resultOrder = $this->OrderModel->destroy($orderid);
        if ($resultOrder === FALSE) {
            $this->error($this->OrderModel->getError());
        }
        $resultOrderProduct = $this->OrderProductModel->destroy($OrderProId);
        if ($resultOrderProduct === FALSE) {
            $this->error($this->OrderProductModel->getError());
        }
        if ($resultOrder === FALSE && $resultOrderProduct  === FALSE) {
            $this->error('删除失败');
        } else {
            $this->success('删除成功');
        }
    }
    //查询单个订单详情信息
    public function info()
    {
        $userid = $this->request->param('userid');

        $orderid = $this->request->param('orderid');

        $user = $this->UserModel->find($userid);

        if (!$user) {
            $this->error('用户不存在，请重新注册');
        }

        /**
         * 订单表数据
         * 订单商品表
         * 商品表
         * 用户收货地址
         */

        // 订单
        $order = $this->OrderModel->find($orderid);

        // 订单商品
        $OrderProduct = $this->OrderProductModel->with('product')->where(['orderid' => $orderid])->select();

        // 收货地址
        $Address = $this->UserAddressModel->with(['provinces', 'citys', 'districts'])->find($order['addrid']);

        if (!$order || !$OrderProduct || !$Address) {
            $this->error('订单不存在，请重新选择');
        }

        $data = [
            'order' => $order,
            'OrderProduct' => $OrderProduct,
            'address' => $Address
        ];

        $this->success('查询成功', null, $data);
    }
}
